﻿namespace MapleRock.P2PEmulator.Core.Events
{
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.IO;
  using System.Linq;
  using System.Text;

  public class BroadcastEvent : BaseEvent
  {
    public BroadcastEvent(uint timestamp, uint fromId, uint cityId)
      : base(EventType.Broadcast, timestamp)
    {
      if (0 == fromId)
      {
        throw new ArgumentException("From identifier must be greater than zero.");
      }

      if (0 == cityId)
      {
        throw new ArgumentException("City identifier must be greater than zero.");
      }

      this.FromId = fromId;
      this.CityId = cityId;
    }

    public uint FromId { get; private set; }

    public uint CityId { get; private set; }

    public override void Deserialize(BinaryReader input)
    {
      base.Deserialize(input);

      this.FromId = input.ReadUInt32();
      if (0 == this.FromId)
      { 
        throw new FormatException("[EVENTS]: FromId must be greater than zero.");
      }

      this.CityId = input.ReadUInt32();
      if (0 == this.CityId)
      {
        throw new FormatException("[EVENTS]: CityId must be greater than zero.");
      }
    }

    public override void Serialize(BinaryWriter output)
    {
      base.Serialize(output);

      Debug.Assert(this.FromId > 0, "this.FromId > 0");
      output.Write(Convert.ToUInt32(this.FromId));

      Debug.Assert(this.CityId > 0, "this.CityId > 0");
      output.Write(Convert.ToUInt32(this.CityId));
    }

    public override string ToString()
    {
      var str = string.Format("BroadcastEvent;FromId={0};CityId={1}", this.FromId, this.CityId);
      return str;
    }
  }
}
